// 处理关键字位置搜索

var A_markerSel = null;
var B_markerSel = null;
var windowsArr = [];
var marker = [];
var A_Select = 0, B_Select = 0, C_Select = 0;

function findRstById(targetId){
    var Rst;
    switch (targetId){
		case "keyword_A" :
			Rst = "result_A";
			break;
		case "keyword_B" :
			Rst = "result_B";
			break;
        default:
            Rst = "result_A";
	}
    return Rst;
}

function findIdByRst(targetRst){
    var Id;
    switch (targetRst){
        case "result_A" :
            Id = "keyword_A";
            break;
        case "result_B" :
            Id = "keyword_B";
            break;
        default :
            Id = "keyword_A";
    }
    return Id;
}

//监听鼠标事件
function doAEvent(event){
    return keydown(event, 'keyword_A');
}

function doBEvent(event){
    return keydown(event,'keyword_B');
}

function keydown(event,targetId){
	var key = (event||window.event).keyCode;
	// var targetId = "keyword_A";
	var targetRst = findRstById(targetId);//"result_A";

	var result = document.getElementById(targetRst)
	var cur = result.curSelect;
	if(key===40){//down
	    if(cur + 1 < result.childNodes.length){
	        if(result.childNodes[cur]){
	            result.childNodes[cur].style.background='';
	        }
	        result.curSelect=cur+1;
	        result.childNodes[cur+1].style.background='#CAE1FF';
	        document.getElementById(targetId).value = result.tipArr[cur+1].name;
	    }
	}else if(key===38){//up
	    if(cur-1>=0){
	        if(result.childNodes[cur]){
	            result.childNodes[cur].style.background='';
	        }
	        result.curSelect=cur-1;
		       result.childNodes[cur-1].style.background='#CAE1FF';
	        document.getElementById(targetId).value = result.tipArr[cur-1].name;
	    }
	}else if(key === 13){
        var res = document.getElementById(targetRst);
		if(res && res['curSelect'] !== -1){
			selectResult(document.getElementById(targetRst).curSelect, targetRst);
		}
    }else{
//        console.log(targetId + ", " + targetRst);
        autoSearch(targetId, targetRst);
    }
}

//输入提示
function autoSearch(targetId, targetRst) {
    var keywords = document.getElementById(targetId).value;
    //加载输入提示插件
        AMap.service(["AMap.Autocomplete"], function() {
        var autoOptions = {
            city: g_City,
            type: "交通设施服务|交通设施服务|商务住宅|住宿服务|公司企业"
        };
        g_AutoSearch = new AMap.Autocomplete(autoOptions);
        //查询成功时返回查询结果
        if ( keywords && keywords.length > 0) {
            g_AutoSearch.search(keywords, function(status, result){
            	autocomplete_CallBack(result,targetRst);
            });
        }
        else {
            document.getElementById(targetRst).style.display = "none";
        }
    });
}   
//输出输入提示结果的回调函数
function autocomplete_CallBack(data,targetRst) {
    console.log("autocomplete_cb: " + targetRst);
    var resultStr = "";
    var tipArr = data.tips;
    if (tipArr && tipArr.length>0) {
        var tipCount = tipArr.length > 5 ? 5 : tipArr.length;
        for (var i = 0; i < tipCount; i++) {
            if ('result_A' == targetRst)
            resultStr += "<div id='divid_A" + (i + 1) + "' onmouseover='openMarkerTipById(" + (i + 1)
                        + ",this)' onclick='selectA(" + i + ")' onmouseout='onmouseout_MarkerStyle(" + (i + 1)
                        + ",this)' style=\"font-size: 13px;cursor:pointer;padding:5px 5px 5px 5px;\"" + "data=" + tipArr[i].adcode + ">" + tipArr[i].name + "<span style='color:#C1C1C1;'>"+ tipArr[i].district + "</span></div>";
            else if ('result_B' == targetRst){
                          resultStr += "<div id='divid_B" + (i + 1) + "' onmouseover='openMarkerTipById(" + (i + 1)
                        + ",this)' onclick='selectB(" + i + ")' onmouseout='onmouseout_MarkerStyle(" + (i + 1)
                        + ",this)' style=\"font-size: 13px;cursor:pointer;padding:5px 5px 5px 5px;\"" + "data=" + tipArr[i].adcode + ">" + tipArr[i].name + "<span style='color:#C1C1C1;'>"+ tipArr[i].district + "</span></div>";  
            }
        }
    }
    else  {
        resultStr = " π__π 亲,人家找不到结果!<br />要不试试：<br />1.请确保所有字词拼写正确<br />2.尝试不同的关键字<br />3.尝试更宽泛的关键字";
    }
    document.getElementById(targetRst).curSelect = -1;
    document.getElementById(targetRst).tipArr = tipArr;
    document.getElementById(targetRst).innerHTML = resultStr;
    document.getElementById(targetRst).style.display = "block";
}

//输入提示框鼠标滑过时的样式
function openMarkerTipById(pointid, thiss) {  //根据id打开搜索结果点tip 
	thiss.style.background = '#CAE1FF';
}
		 
//输入提示框鼠标移出时的样式
function onmouseout_MarkerStyle(pointid, thiss) {  //鼠标移开后点样式恢复 
    thiss.style.background = "";
}

//从输入提示框中选择关键字并查询
function selectA(index){
    A_Select = 1;
    B_Select = 0;
    C_Select = 0;
    return selectResult(index, 'result_A');
}

function selectB(index){
    A_Select = 0;
    B_Select = 1;
    C_Select = 0;
    return selectResult(index, 'result_B');
}

function selectResult(index, targetRst) {
    if(index<0){
        return;
    }
    var keyRst = targetRst;
    var keyword = findIdByRst(keyRst);
    console.log("selectResult: "+ keyword + " : " + keyRst);
    if (navigator.userAgent.indexOf("MSIE") > 0) {
        document.getElementById(keyword).onpropertychange = null;
        document.getElementById(keyword).onfocus = focus_callback;
    }
    //截取输入提示的关键字部分
    var text = "";
    var cityCode = "";
    if ('result_A' == targetRst){
        text = document.getElementById("divid_A" + (index + 1)).innerHTML.replace(/<[^>].*?>.*<\/[^>].*?>/g,"");
        cityCode = document.getElementById("divid_A" + (index + 1)).getAttribute('data');
    }
    else if ('result_B' == targetRst) {
        text = document.getElementById("divid_B" + (index + 1)).innerHTML.replace(/<[^>].*?>.*<\/[^>].*?>/g,"");
        cityCode = document.getElementById("divid_B" + (index + 1)).getAttribute('data');
    }
	
    document.getElementById(keyword).value = text;
    document.getElementById(keyRst).style.display = "none";
    //根据选择的输入提示关键字查询
    g_Map.plugin(["AMap.PlaceSearch"], function() {       
        g_PlaceSearch = new AMap.PlaceSearch();  //构造地点查询类
        AMap.event.addListener(g_PlaceSearch, "complete", placeSearch_CallBack); //查询成功时的回调函数
        g_PlaceSearch.setCity(g_City);
        g_PlaceSearch.setType("交通设施服务|交通设施服务|商务住宅|住宿服务|公司企业")
        g_PlaceSearch.search(text);  //关键字查询查询
    });
	}
	 
//定位选择输入提示关键字
function focus_callback() {
    if (navigator.userAgent.indexOf("MSIE") > 0) {
        document.getElementById(keyword).onpropertychange = autoSearch;
   }
}
	 
//输出关键字查询结果的回调函数
function placeSearch_CallBack(data) {
        if (A_Select && !B_Select){
            if (A_markerSel) A_markerSel.hide();
        }else if (B_Select && !A_Select){
            if (B_markerSel) B_markerSel.hide();
        }
	    //清空地图上的InfoWindow和Marker
        marker = [];
        windowsArr = [];
	    var poiArr = data.poiList.pois;
	    var resultCount = !C_Select ? ( poiArr.length > 3 ? 3 : poiArr.length ) : (poiArr.length > 5 ? 5 : poiArr.length);
	    for (var i = 0; i < resultCount; i++) {
		          addmarker(i, poiArr[i]);
		    }
       if(C_Select){
            g_Map.setFitView();
       }else {
            g_Map.setZoomAndCenter(17,poiArr[0].location);
       }

}
 
//添加查询结果的marker&infowindow   
function addmarker(i, d) {
    var lngX = d.location.getLng();
    var latY = d.location.getLat();
    var markerOption = {
        map:g_Map,
        icon:A_Marker.getIcon(),
        position:new AMap.LngLat(lngX, latY),
        animation: "AMAP_ANIMATION_BOUNCE"//"AMAP_ANIMATION_DROP"
    };
    if (B_Select && !A_Select){
        markerOption.icon = B_Marker.getIcon();
    }else if (C_Select){
        markerOption.icon = C_Marker.getIcon();
    }
    var mar = new AMap.Marker(markerOption);
    marker.push(mar);
		 
    var infoWindow = new AMap.InfoWindow({
        content:"<h3><font color=\"#00a6ac\">  " + (i + 1) + ". " + d.name + "</font></h3>" + TipContents(d.type, d.address, lngX, latY)+"<input onclick='atPoint(" + i + ")' type=\"button\" value=\"哇，就是这里！\">",
        size:new AMap.Size(300, 0),
        autoMove:true, 
        offset:new AMap.Pixel(0,-30)
    });
    if (C_Select){
        infoWindow.setContent("<h3><font color=\"#ff00b3\">  " + (i + 1) + ". " + d.name + "</font></h3>" + TipContentsTel(d.type, d.address, d.tel)+"<input onclick='goPoint(" + i + ")' type=\"button\" value=\"耶，约在这里！\">");
    }
    var aa = function (e) {
        infoWindow.open(g_Map, mar.getPosition());
    };
    var windowListener = AMap.event.addListener(mar, "mouseover", aa);
    var windowArr = {
        info : infoWindow,
        listener: windowListener
    };
    windowsArr.push(windowArr);
}
		 
//infowindow显示内容
function TipContents(type, address, lngX, latY) {  //窗体内容
    if (type == "" || type == "undefined" || type == null || type == " undefined" || typeof type == "undefined") {
        type = "暂无";
    }
    if (address == "" || address == "undefined" || address == null || address == " undefined" || typeof address == "undefined") {
        address = "暂无";
    }
   var str = "  地址：" + address + "<br /> 经度：" + lngX + ",  纬度：" +latY;//+ " <br /> " 类型：" + type;
   return str;
}

// 确定地点
function atPoint(index){
    if(A_Select && !B_Select){
        A_Position = marker[index].getPosition();
        A_markerSel = marker[index];
        console.log("Hey, due. I am from A_Select.");
    }
    else if(B_Select && !A_Select){
        B_Position = marker[index].getPosition();
        B_markerSel = marker[index];
        console.log("Hey, due. I am from B_Select.");
    }
    
    for (var i = 0 ; i < marker.length; i++){
        if ( i != index){
            marker[i].hide();
        }
        windowsArr[i].info.close();
        AMap.event.removeListener(windowsArr[i].listener);
    }
    g_Map.setFitView();
}

function goPoint(index){
    C_Position = marker[index].getPosition();
    doCposition();
}